package com.zhentao.service.impl;
import com.zhentao.config.MinioConfig;
import com.zhentao.config.MinioConfigProperties;
import com.zhentao.service.FileService;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


@Service
@Import(MinioConfig.class)
@EnableConfigurationProperties(MinioConfigProperties.class)
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConfigProperties monitorConfigProperties;

    @SneakyThrows
    @Override
    public String uploadHtml(String fileName, InputStream inputStream) {


        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(monitorConfigProperties.getBucketName())
                .contentType("text/html")
                .object(fileName)
                .stream(inputStream, inputStream.available(), -1)
                .build();

        ObjectWriteResponse response = minioClient.putObject(putObjectArgs);

        //获取地址
        String path = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());

        return path;
    }

    @Override
    public String uploadImage(String fileName, InputStream inputStream) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(monitorConfigProperties.getBucketName())
                .contentType("image/jpg")
                .object(fileName)
                .stream(inputStream, inputStream.available(), -1)
                .build();

        ObjectWriteResponse response = minioClient.putObject(putObjectArgs);

        //获取地址
        String path = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());

        return path;
    }
}
